import { Col, Row, List, Drawer } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import { Avatar, Card } from 'antd';
import axios from 'axios';
import * as Echarts from 'echarts'
import _ from 'lodash'

const { Meta } = Card;

export default function Home() {
    const [viewList, setviewList] = useState([])
    const [starList, setstarList] = useState([])
    const [visible, setvisible] = useState(false)
    const [pieChart, setpieChart] = useState(null)
    const [allList,setAllList] = useState([])
    const barRef = useRef();
    const pieRef = useRef();

    // 浏览最高数据
    useEffect(() => {
        axios.get(`/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6`).then(res => {
            // console.log(res.data);
            setviewList(res.data)
        })
    }, [])

    // 点赞最高数据
    useEffect(() => {
        axios.get(`/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6`).then(res => {
            // console.log(res.data);
            setstarList(res.data)
        })
    }, [])

    // 柱状图数据
    useEffect(() => {
        axios.get(`/news?publishState=2&_expand=category`).then(res => {
            // console.log();
            // console.log(res.data);
            renderBarView(_.groupBy(res.data, item => item.category.title))
            setAllList(res.data)
        })

    }, [])
    // 柱状图
    const renderBarView = (obj) => {
        // 基于准备好的dom，初始化echarts实例
        var myChart = Echarts.init(barRef.current);
        // 指定图表的配置项和数据
        var option = {
            title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(obj),
            },
            yAxis: {
                // 最小间隔
                minInterval: 1
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(obj).map(item => item.length)
                }
            ]
        };

        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);

    }
    // 饼状图
    const renderPieView = (obj) => {
        // 数据处理
        var currentList =allList.filter(item=>item.author===username)
        // console.log(currentList);
        var groupObj=_.groupBy(currentList,item=>item.category.title)
        // console.log(groupObj);
        var List=[]
        for(var i in groupObj){
            List.push({
                name:i,
                value:groupObj[i].length
            })
        }
        // console.log(List);
        var myChart; 
        if(!pieChart){
            myChart= Echarts.init(pieRef.current);
            setpieChart(myChart)
        }else{
            myChart=pieChart;
        }
        var option = {
            title: {
                text: '当前用户新闻分类图示',
                // subtext: '',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '发布数量',
                    type: 'pie',
                    radius: '50%',
                    data: List,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        option && myChart.setOption(option);

    }

    const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem("token"))
    return (
        <div>
            <div className="site-card-wrapper">
                {/* 栅栏布局 */}
                <Row gutter={16}>
                    <Col span={8}>
                        <Card title="用户最常浏览" bordered={true}>
                            <List
                                size="small"
                                dataSource={viewList}
                                renderItem={item => (
                                    <List.Item>
                                        <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                                    </List.Item>
                                )}
                            />
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card title="用户点赞最多" bordered={false}>
                            <List
                                size="small"
                                dataSource={starList}
                                renderItem={item => (
                                    <List.Item>
                                        <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                                    </List.Item>
                                )}
                            />
                        </Card>
                    </Col>
                    <Col span={8}>
                        <Card
                            cover={
                                <img
                                    alt="example"
                                    src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
                                />
                            }
                            actions={[
                                // 抽屉饼状图开关
                                <SettingOutlined key="setting" onClick={() => {
                                    setvisible(true)
                                    setTimeout(() => {
                                        // init初始化
                                        renderPieView()
                                    }, 0);
                                }} />,
                                <EditOutlined key="edit" />,
                                <EllipsisOutlined key="ellipsis" />,
                            ]}
                        >
                            <Meta
                                avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
                                title={username}
                                description={
                                    <div>
                                        <b>{region ? region : '全球'}</b>
                                        <span style={{ marginLeft: '30px' }}>{roleName} </span>
                                    </div>
                                }
                            />
                        </Card>
                    </Col>
                </Row>

                {/* 抽屉 */}
                <Drawer title="个人新闻分类" placement="right" onClose={() => {
                    setvisible(false)
                }} open={visible} width='500px'>
                    <div ref={pieRef} id="main" style={{
                        width: '100%',
                        height: '400px',
                        marginTop: '30px'
                    }}></div>
                </Drawer>

                {/* 柱状图 */}
                <div ref={barRef} id="main" style={{
                    width: '100%',
                    height: '500px',
                    marginTop: '30px'
                }}></div>
            </div>
        </div>
    )
}
